import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';

import MemberLayout from '@/component/member/Layout';
import MTable from '@/component/common/MTable';
import { Pagination, Form, Input, Select, Switch, Spin } from 'antd';
import _ from 'lodash';

import MModal from '@/component/common/MModal';
import ModifyPswModal from '@/component/member/ModifyPswModal';
import CreateStoreModal from '@/component/member/CreateStoreModal';

import style from './style.scss';

const FormItem = Form.Item;
const Option = Select.Option;
const mConfirm = MModal.confirm;

import FilterListPage from '@/component/common/FilterListPage';

import ApiHelper from '@/store/ApiHelper';
import { account_list, delete_member as api_delete_member,
    modify_store_auth as api_modify_store_auth } from '@/constants/ApiTypes';
import format from '@/tool/format';
import StoreAuthTypes from '@/constants/StoreAuthTypes';

// const testData = [
//     { a: '解放路店', b: '1234567890@qq.com', c: '120套', d: '300套', e: '80套', f: '1234567元', g: '123456次', j: '2017-10-08 22:54' },
//     { a: '解放路店', b: '1234567890@qq.com', c: '120套', d: '300套', e: '80套', f: '1234567元', g: '123456次', j: '2017-10-08 22:54' }
// ];

class Filter extends Component {
    static propTypes = {
        form: PropTypes.any,
        onSubmit: PropTypes.func
    };
    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                if (this.props.onSubmit) {
                    for (let key in values) {
                        if (values[key] === '') delete values[key];
                    }
                    this.props.onSubmit(values);
                }
            }
        });
    };
    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form layout="inline" onSubmit={this.handleSubmit}>
                <FormItem label="账号">
                    {getFieldDecorator('account', {
                        initialValue: ''
                    })(
                        <Input/>
                    )}
                </FormItem>
                <FormItem>
                    <button className={style['submit-btn']} type="submit">搜索</button>
                </FormItem>
            </Form>
        );
    }
}
const FilterWrapped = Form.create()(Filter);

class ModifyPowerModal extends Component {
    constructor(props) {
        super(props);
    }
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        store_id: PropTypes.number.isRequired,
        rules: PropTypes.string.isRequired
    };
    defaultState = {
        spinning: false,
        newRules: []
    };
    state = this.defaultState;
    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState(this.defaultState);
            this.buildRules(nextProps.rules);
        }
    }
    //构造数组控制switch
    buildRules = rules => {
        const old_rules = rules.split(',');
        let _rules = [];
        StoreAuthTypes.forEach(val => {
            if (_.indexOf(old_rules, `${val.id}`) > -1) {
                _rules.push({ id: val.id, name: val.name, checked: true });
            } else {
                _rules.push({ id: val.id, name: val.name, checked: false });
            }
        });
        this.setState({ newRules: _rules });
    };
    okClick = async () => {
        this.setState({
            spinning: true
        });

        let rules = [];
        this.state.newRules.forEach(val => {
            if (val.checked) {
                rules.push(val.id);
            }
        });
        const data = {
            store_id: this.props.store_id,
            rules: rules.join(',')
        };

        const result = await ApiHelper.requestPost(api_modify_store_auth, data);
        if (result.status) {
            MModal.success({ title: '操作成功', content: '操作成功', duration: 1.5 });
            this.props.onClose(true);
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
        this.setState({
            spinning: false
        });
    }
    switchOnChange = (checked, id) => {
        let newRules = this.state.newRules.map(val => {
            if (val.id == id) val.checked = checked;
            return val;
        });
        this.setState({ newRules });
    };
    render() {
        const { visible, onClose } = this.props;
        const { newRules } = this.state;
        const { okClick } = this;
        const switches = newRules.map((val, index) =>
            <div key={index} className={style['label-item']}>
                <span className={style['label-text']}>{val.name}</span>
                <Switch checked={val.checked} onChange={checked => this.switchOnChange(checked, val.id)} />
            </div>
        );
        return (
            <MModal visible={visible} onClose={onClose} width={425} height={415}>
                <Spin tip="loading" spinning={this.state.spinning} delay={150}>
                    <div className={style['modify-power-modal']}>
                        <div className={style['modal-title']}>
                            权限设置
                        </div>
                        <div className={style['modal-content']}>
                            {switches}
                        </div>
                        <div className={style['oper-btn-group']}>
                            <a className={style['ok-btn']} href="javascript:void(0);" onClick={okClick}>修改</a>
                        </div>
                    </div>
                </Spin>
            </MModal>
        );
    }
}

@observer class MemberStore extends FilterListPage {
    constructor(props) {
        super(props);
        const state = {
            modifyPswModalVisible: false,
            modifyPswModalProps: {
                account_name: '',
                account_id: 0
            },
            modifyPowerModalVisible: false,
            modifyPowerModalProps: {
                store_id: 0,
                rules: ''
            },
            createStoreModalVisible: false
        };
        this.listApiType = account_list;
        this.defaultQuery = {
            account_type: 1 //门店账号
        };
        this._setDefaultState(state);
    }
    async pageDidMount() {
        this._setState({ loading: false });
    }
    showModifyPswModal = (account_name, account_id) => {
        this.setState({
            modifyPswModalProps: {
                account_name: account_name,
                account_id: account_id
            },
            modifyPswModalVisible: true
        });
    };
    closeModifyPswModal = () => {
        this.setState({ modifyPswModalVisible: false });
    };
    showModifyPowerModal = (store_id, rules) => {
        this.setState({
            modifyPowerModalProps: {
                store_id: store_id,
                rules: rules
            },
            modifyPowerModalVisible: true
        });
    };
    closeModifyPowerModal = (refresh = false) => {
        if (refresh) this.refresh();
        this.setState({ modifyPowerModalVisible: false });
    };
    deleteConfirm = (account_id) => {
        mConfirm({
            title: '是否删除该账号',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            onOk: async () => {
                //账号删除
                const data = { org_uid: account_id };
                const result = await ApiHelper.requestPost(api_delete_member, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '操作成功', duration: 1.5 });
                    this.refresh();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() {}
        });
    };
    showCreateStoreModal = () => {
        this.setState({ createStoreModalVisible: true });
    };
    closeCreateStoreModal = (refresh = false) => {
        if (refresh == true) this.refresh();
        this.setState({ createStoreModalVisible: false });
    };
    render() {
        const { modifyPswModalVisible, modifyPswModalProps, modifyPowerModalVisible, modifyPowerModalProps,
            createStoreModalVisible, dataList, spinning } = this.state;
        const { showModifyPswModal, closeModifyPswModal,
            deleteConfirm, showModifyPowerModal, closeModifyPowerModal,
            showCreateStoreModal, closeCreateStoreModal
        } = this;

        const account_oper = (text, record, dataIndex) => {
            return (
                <div className="oper-text">
                    <a href="javascript:void(0);" onClick={() => { showModifyPswModal(record.mobile, record.account_id) }}>修改密码</a>
                    {record.can_delete && '/'}
                    {record.can_delete && <a href="javascript:void(0);" onClick={() => { deleteConfirm(record.account_id) }}>删除</a>}
                </div>
            );
        };

        const modify_power = (text, record, dataIndex) => <a href="javascript:void(0);" onClick={() => { showModifyPowerModal(record.store_id, record.rules) }}>设置</a>;
        const last_login = (text, record, dataIndex) => {
            if (text == 0) return '从未登录';
            return format.timeString(text);
        };

        const columns = [
            { title: '门店', dataIndex: 'store_name', align: 'middle' },
            { title: '账号', dataIndex: 'account', align: 'middle' },
            { title: '上架房源', dataIndex: 'house_up_count', align: 'middle' },
            { title: '签约合同', dataIndex: 'all_contract', align: 'middle' },
            { title: '分期', dataIndex: 'stage_contract', align: 'middle' },
            { title: '利润收入', dataIndex: 'profit', align: 'middle', render: (text, record, dataIndex) => isNaN(text) ? text : text / 100 + '元' },
            { title: '点击量', dataIndex: 'view_count', align: 'middle' },
            { title: '权限设置', dataIndex: 'h', align: 'middle',  render: modify_power },
            { title: '账号操作', dataIndex: 'i', align: 'middle', render: account_oper },
            { title: '最后一次登录', dataIndex: 'last_login_time', align: 'middle', render: last_login }
        ];

        return (
            <MemberLayout plusOnClick={showCreateStoreModal} loading={this.state.loading}>
                <CreateStoreModal visible={createStoreModalVisible} onClose={closeCreateStoreModal} />
                <div className={style['top-filter']}>
                    <FilterWrapped onSubmit={this.getDataListWithFilter} />
                </div>
                <MTable columns={columns} dataSource={dataList} spinning={spinning}/>
                <ModifyPswModal visible={modifyPswModalVisible} onClose={closeModifyPswModal} {...modifyPswModalProps} />
                <ModifyPowerModal visible={modifyPowerModalVisible} onClose={closeModifyPowerModal} {...modifyPowerModalProps} />
                <div className="pagination">
                    {this.state.total > 0 && <Pagination showQuickJumper current={this.state.current_page} pageSize={10} total={this.state.total} onChange={this.pageOnChange} />}
                </div>
            </MemberLayout>
        );
    }
}

export default MemberStore;